using AutoMapper;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using ContentmanagementBase.Domain;
using ContentmanagementBase.Domain.Enums;
using ContentmanagementBaseRead.API.Applications.Commands.Questions;
using ContentmanagementBaseRead.API.Dtos;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel;
using System.Reflection;

namespace ContentmanagementBaseRead.API.Applications.Commandhandlters.Questions
{
    /// <summary>
    /// 获取常见问题信息列表命令处理
    /// </summary>
    public class GetProblemListCommandHandler : IRequestHandler<GetProblemListCommand, ApiPaging<List<ProblemListDto>>>
    {
        /// <summary>
        /// 问题仓储
        /// </summary>
        private readonly IBaseRepository<ProblemManagementModel> _problemRepository;
        /// <summary>
        /// 映射器
        /// </summary>
        private readonly IMapper _mapper;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<GetProblemListCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="problemRepository">问题仓储</param>
        /// <param name="mapper">映射器</param>
        /// <param name="logger">日志</param>
        public GetProblemListCommandHandler(
            IBaseRepository<ProblemManagementModel> problemRepository,
            IMapper mapper,
            ILogger<GetProblemListCommandHandler> logger)
        {
            _problemRepository = problemRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取常见问题列表命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        public async Task<ApiPaging<List<ProblemListDto>>> Handle(GetProblemListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始获取常见问题列表，页码：{PageIndex}，每页数量：{PageSize}", 
                    request.PageIndex, request.PageSize);

                // 获取所有问题数据（排除已删除的）
                var query = _problemRepository.GetAll().AsNoTracking();

                // 应用搜索条件
                if (!string.IsNullOrEmpty(request.ProblemTitle))
                {
                    query = query.Where(x => x.ProblemTitle.Contains(request.ProblemTitle));
                    _logger.LogDebug("应用标题搜索条件：{Title}", request.ProblemTitle);
                }

                if (request.ProblemType.HasValue)
                {
                    query = query.Where(x => x.ProblemType == request.ProblemType.Value);
                    _logger.LogDebug("应用分类搜索条件：{ProblemType}", request.ProblemType.Value);
                }

                
                // 按创建时间倒序排列
                query = query.OrderByDescending(x => x.CreatedTime);

                // 获取总数量
                var totalCount = await query.CountAsync(cancellationToken);
                _logger.LogDebug("查询到总记录数：{TotalCount}", totalCount);

                // 计算分页信息
                var pageCount = (int)Math.Ceiling((double)totalCount / request.PageSize);
                var skip = (request.PageIndex - 1) * request.PageSize;

                // 获取分页数据
                var pagedData = await query.Skip(skip).Take(request.PageSize).ToListAsync(cancellationToken);
                _logger.LogDebug("获取分页数据，实际返回数量：{Count}", pagedData.Count);

                // 映射到DTO并设置分类描述
                var problemDtos = new List<ProblemListDto>();
                foreach (var problem in pagedData)
                {
                    var dto = _mapper.Map<ProblemListDto>(problem);
                    // 获取分类描述
                    dto.ProblemTypeDescription = GetEnumDescription(problem.ProblemType);
                    problemDtos.Add(dto);
                }

                return new ApiPaging<List<ProblemListDto>>
                {
                    code = ResultEnumCode.Ok,
                    message = "常见问题列表获取成功",
                    data = problemDtos,
                    TotalCount = totalCount,
                    PageCount = pageCount,
                   
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取常见问题列表过程中发生异常，页码：{PageIndex}，每页数量：{PageSize}", 
                    request.PageIndex, request.PageSize);

                return new ApiPaging<List<ProblemListDto>>
                {
                    code = ResultEnumCode.fails,
                    message = $"获取常见问题列表异常：{ex.Message}",
                    data = new List<ProblemListDto>(),
                    TotalCount = 0,
                    PageCount = 0,
                  
                };
            }
        }

        /// <summary>
        /// 获取枚举描述
        /// </summary>
        /// <param name="enumValue">枚举值</param>
        /// <returns>描述</returns>
        private string GetEnumDescription(FAQCategoryEnum enumValue)
        {
            var fieldInfo = typeof(FAQCategoryEnum).GetField(enumValue.ToString());
            var descriptionAttribute = fieldInfo?.GetCustomAttribute<DescriptionAttribute>();
            return descriptionAttribute?.Description ?? enumValue.ToString();
        }
    }
} 